package com.dp.temp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dp.io.ESN;
import com.dp.io.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class uploadBBFakeInfo {



    @Autowired
    private JdbcTemplate jdbcTemplate;


//    自动上传包保数据
//    @Scheduled(cron = "0 16 23 1,7 * ?")
//    @PostConstruct
    public void uploadZYBBFakeInfo() {
        //由计划自动生成包保任务记录
        System.out.println("----------------------------------------------------自动上传主要包保任务记录");
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap("select token from basic_company");
            List<Map<String, Object>> checkPlainInfo =  findCheckPlainInfoBB("1");
            String httpUrl = "http://218.26.86.44:9301/doublePre/hiddenDangerRecord";
            if(checkPlainInfo.size() != 0){
                int a = 0;
                Thread.sleep(70000);
                if(checkPlainInfo.size() > 100){
                    for (; a < checkPlainInfo.size()/100 ; a++) {
                        JSONObject jsonObject = JSONUtil.SUCCESSJson(checkPlainInfo.stream().skip(a*100).limit((a+1)*100).collect(Collectors.toList()), "100", "请求成功");
                        jsonObject.put("token",map.get("token"));
                        jsonObject.put("data", jsonObject.get("info"));
                        String[] msg = http(httpUrl, jsonObject, map.get("token").toString());
                        Thread.sleep(70000);
                    }
                }
                JSONObject jsonObject = JSONUtil.SUCCESSJson(checkPlainInfo.stream().skip(a*100).collect(Collectors.toList()), "100", "请求成功");
                jsonObject.put("token",map.get("token"));
                jsonObject.put("data", jsonObject.get("info"));
                String[] msg = http(httpUrl, jsonObject, map.get("token").toString());
                Thread.sleep(70000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @Scheduled(cron = "0 14 23 1,4,7,10 * ?")
//    @PostConstruct
    public void uploadJSBBFakeInfo() {
        //由计划自动生成包保任务记录
        System.out.println("----------------------------------------------------自动上传技术包保任务记录");
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap("select token from basic_company");
            List<Map<String, Object>> checkPlainInfo =  findCheckPlainInfoBB("2");
            String httpUrl = "http://218.26.86.44:9301/doublePre/hiddenDangerRecord";
            if(checkPlainInfo.size() != 0){
                int a = 0;
                Thread.sleep(70000);
                if(checkPlainInfo.size() > 100){
                    for (; a < checkPlainInfo.size()/100 ; a++) {
                        JSONObject jsonObject = JSONUtil.SUCCESSJson(checkPlainInfo.stream().skip(a*100).limit((a+1)*100).collect(Collectors.toList()), "100", "请求成功");
                        jsonObject.put("token",map.get("token"));
                        jsonObject.put("data", jsonObject.get("info"));
                        String[] msg = http(httpUrl, jsonObject, map.get("token").toString());
                        Thread.sleep(70000);
                    }
                }
                JSONObject jsonObject = JSONUtil.SUCCESSJson(checkPlainInfo.stream().skip(a*100).collect(Collectors.toList()), "100", "请求成功");
                jsonObject.put("token",map.get("token"));
                jsonObject.put("data", jsonObject.get("info"));
                String[] msg = http(httpUrl, jsonObject, map.get("token").toString());
                Thread.sleep(70000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Scheduled(cron = "0 10 23 ? * THU")
    @PostConstruct
    public void uploadCZBBFakeInfo() {
        //由计划自动生成包保任务记录
        System.out.println("----------------------------------------------------自动上传操作包保任务记录");
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap("select token from basic_company");
            List<Map<String, Object>> checkPlainInfo =  findCheckPlainInfoBB("3");
            String httpUrl = "http://218.26.86.44:9301/doublePre/hiddenDangerRecord";
            if(checkPlainInfo.size() != 0){
                int a = 0;
                Thread.sleep(70000);
                if(checkPlainInfo.size() > 100){
                    for (; a < checkPlainInfo.size()/100 ; a++) {
                        JSONObject jsonObject = JSONUtil.SUCCESSJson(checkPlainInfo.stream().skip(a*100).limit((a+1)*100).collect(Collectors.toList()), "100", "请求成功");
                        jsonObject.put("token",map.get("token"));
                        jsonObject.put("data", jsonObject.get("info"));
                        String[] msg = http(httpUrl, jsonObject, map.get("token").toString());
                        Thread.sleep(70000);
                    }
                }
                JSONObject jsonObject = JSONUtil.SUCCESSJson(checkPlainInfo.stream().skip(a*100).collect(Collectors.toList()), "100", "请求成功");
                jsonObject.put("token",map.get("token"));
                jsonObject.put("data", jsonObject.get("info"));
                String[] msg = http(httpUrl, jsonObject, map.get("token").toString());
                Thread.sleep(70000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Map<String, Object>> findCheckPlainInfoBB(String type) {
        List<String> strings = new ArrayList<>();
        strings.add("863946065700197");
        strings.add("868327063647166");
        strings.add("867738065175744");
        strings.add("864847053800727");
        Random random = new Random();
        String imei = strings.get(random.nextInt(strings.size()));
        String sql = " SELECT UUID() AS id,'" + getComCode() + "' AS companyCode, id AS checkTaskId, DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s') AS checkTime, SUBSTRING_INDEX(UNAME, ',', 1) AS createBy, '1' AS isDefend ,(SELECT telephone FROM sys_user WHERE id = SUBSTRING_INDEX(UID, ',', 1) limit 1) AS createByMobile ,'"+ imei +"'AS mobileMe FROM hd_check_plain WHERE DELETED = '0' AND WORK_TYPE = '"+ type +"' AND OIFRISK = '0' ";
        return jdbcTemplate.queryForList(sql);
    }


    //自动上传日常任务数据

//    @Scheduled(cron = "0 10 23 ? * THU")
//    @PostConstruct
    public void uploadFakeInfo() {
        //由计划自动生成任务记录数据上传
        System.out.println("----------------------------------------------------自动上传任务记录");
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap("select token from basic_company");
            List<Map<String, Object>> checkPlainInfo =  findCheckPlainInfo();
            String httpUrl = "http://218.26.86.44:9301/doublePre/hiddenDangerRecord";
            if(checkPlainInfo.size() != 0){
                int a = 0;
                Thread.sleep(70000);
                if(checkPlainInfo.size() > 100){
                    for (; a < checkPlainInfo.size()/100 ; a++) {
                        JSONObject jsonObject = JSONUtil.SUCCESSJson(checkPlainInfo.stream().skip(a*100).limit((a+1)*100).collect(Collectors.toList()), "100", "请求成功");
                        jsonObject.put("token",map.get("token"));
                        jsonObject.put("data", jsonObject.get("info"));
                        String[] msg = http(httpUrl, jsonObject, map.get("token").toString());
                        Thread.sleep(70000);
                    }
                }
                JSONObject jsonObject = JSONUtil.SUCCESSJson(checkPlainInfo.stream().skip(a*100).collect(Collectors.toList()), "100", "请求成功");
                jsonObject.put("token",map.get("token"));
                jsonObject.put("data", jsonObject.get("info"));
                String[] msg = http(httpUrl, jsonObject, map.get("token").toString());
                Thread.sleep(70000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Map<String, Object>> findCheckPlainInfo() {
        List<String> strings = new ArrayList<>();
        strings.add("863946065700197");
        strings.add("868327063647166");
        strings.add("867738065175744");
        strings.add("864847053800727");
        Random random = new Random();
        String imei = strings.get(random.nextInt(strings.size()));
        String sql = " SELECT UUID() AS id,'" + getComCode() + "' AS companyCode, id AS checkTaskId, DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s') AS checkTime, SUBSTRING_INDEX(UNAME, ',', 1) AS createBy, '1' AS isDefend ,(SELECT telephone FROM sys_user WHERE id = SUBSTRING_INDEX(UID, ',', 1) limit 1) AS createByMobile ,'"+ imei +"'AS mobileMe FROM hd_check_plain WHERE DELETED = '0' AND WORK_TYPE = '0' AND OIFRISK = '0' ";
        return  jdbcTemplate.queryForList(sql);
    }

    public String getComCode() {
        return jdbcTemplate.queryForList(" SELECT com_coalcode code FROM basic_company ").get(0).get("code").toString();
    }


    public static String[] http(@RequestParam String url, @RequestBody JSONObject object, String token){
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[] code = new String[2];
        try{
            //创建post连接，连接到对应地址
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            // 我这里利用阿里的fastjson，将Object转换为json字符串;
            // (需要导入com.alibaba.fastjson.JSON包)
            String jsonString = JSON.toJSONString(object);
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            httpPost.setHeader("token", token);
            // 响应模型
            CloseableHttpResponse response = null;
            try {
                // 由客户端执行(发送)Post请求
                response = httpClient.execute(httpPost);
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                System.out.println("响应状态为:" + response.getStatusLine());
                code[0] = String.valueOf(response.getStatusLine().getStatusCode());
                if (responseEntity != null) {
                    System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                    String s = EntityUtils.toString(responseEntity);
                    System.out.println("响应内容为:" +s);
                    System.out.println("当前时间：" + simpleDateFormat.format(date));
                    code[1] = s;
                }
            } catch (ClientProtocolException e) {
                System.out.println("ClientProtocolException异常");
                e.printStackTrace();
            } catch (ParseException e) {
                System.out.println("ParseException异常");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("IOException异常");
                e.printStackTrace();
            } finally {
                try {
                    // 释放资源
                    if (httpClient != null) {
                        httpClient.close();
                    }
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    System.out.println("IOException异常");
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            System.out.println("Exception异常");
            e.printStackTrace();
        }
        return code;
    }




}
